import { getPage, getImage } from '../../utils/config';
import { http, promisify, $toast } from '../../utils/utils';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        getImage: getImage,
    },

    /**
     * 内容--监听输入
     */
    textareaChange(e) {
        const { value } = e.detail;
        const { dataset } = e.currentTarget || e.target;
        const { picList } = this.data;

        picList[dataset.idx].msg = value;

        this.setData({ picList });
    },

    /**
     * 上传图片--微信api
     */
    uploadImgClick(e) {
        const { idx } = e.currentTarget.dataset || e.target.dataset;
        let { picList } = this.data;
        let list = picList[idx].uploadPic;
        let count = picList[idx].picCount - list.length;
        
        promisify(wx.chooseImage)({
            count: count,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
        }).then((res) => {
            //先删除原有数组的最后一个
            list.splice(list.length - 1, 1);
            //后将原有的最后一个加入结尾
            res.tempFilePaths.push(getImage.uploadDefault);
            //生成新的集合
            picList[idx].uploadPic = [].concat(list, res.tempFilePaths);
            this.setData({ picList });
        })
    },

    /**
     * 删除图片--操作数据
     */
    deleteImgClick(e) {
        const { dataset } = e.currentTarget || e.target;
        const { picList } = this.data;
        
        picList[dataset.idx].uploadPic.splice(dataset.id, 1);

        this.setData({ picList });
    },

    /**
     * 发布评论--网络请求
     */
    submitComments() {
        const { userId, orderId } = this.data;

        this.setUploadImage().then((res) => {
            http.post(api.default, {
                data: {
                    action: 'addcomments',
                    userid: userId,
                    comments: JSON.stringify(res),
                    service_score: 0,
                    logistics_score: 0,
                    shipment_score: 0,
                }
            }).then((res) => {
                console.log(res);
                const pages = getCurrentPages()[getCurrentPages().length - 2];
                wx.redirectTo({
                    url: getPage.commentsSuccess,
                    success() {
                        if (pages !== undefined || pages !== null) {
                            pages.appendCommentsOrder(orderId);
                        }
                    }
                })
            })
        })
    },

    /**
     * 上传图片--网络请求
     */
    setUploadImage() {
        return new Promise((resolve, reject) => {
            const { orderId, picList } = this.data;
            let list = [];

            picList.forEach((item, idx) => {
                //生成对象
                list[idx] = {
                    commentid: item.commentid,
                    itemid: item.itemId,
                    content_goods: item.msg,
                    imgPic: item.pic,
                    photo: [],
                    rank_star: 0,
                    rank_str: '',
                    title: item.title,
                };

                if(item.uploadPic.length > 1){
                    for (let i = 0; i < item.uploadPic.length - 1; i++){
                        uploadImage({
                            filePath: item.uploadPic[i],
                            dir: "product",
                            success(res) {
                                list[idx].photo.push({ base64str: res });
                            },
                            fail(res) {
                                $toast(`第${idx}商品，第${i}张图片上传失败`);
                            },
                            complete() {
                                if (idx == picList.length - 1 && i == item.uploadPic.length - 2) {
                                    resolve(list);
                                }
                            },
                        });
                    }
                } else if (idx == picList.length - 1){
                    resolve(list);
                }
            });
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        //判断入口是否带参数
        if (options && JSON.stringify(options) !== '{}') {
            let products = JSON.parse(options.products);
            let picList = [];
            
            products.forEach((item) => {
                picList.push({
                    picCount: 7,
                    uploadPic: [getImage.uploadDefault],
                    msg: '',
                    pic: item.pic,
                    title: item.title,
                    commentid: item.commentId,
                    itemId: item.itemId,
                });
            });

            this.setData({ 
                picList,
                orderId: options.orderId,
                shopName: options.shopName,
            });
        }

        //获取登录用户
        app.getLogin().then((res) => {
            const { user } = res.data;
            this.setData({
                userId: user.user_id
            })
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})